package com.wlxk.crawler.core.manager.qishuta;

import com.wlxk.crawler.core.dao.ArticleDAO;
import com.wlxk.crawler.core.dao.ChapterDAO;
import com.wlxk.crawler.core.enums.SourceEnum;
import com.wlxk.crawler.core.manager.PipelineManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: 21054523
 * @time: 2023/11/16 15:52
 */
@Component
public class QishutaPipeline extends PipelineManager implements Pipeline {

    @Autowired
    private ArticleDAO articleDAO;

    @Autowired
    private ChapterDAO chapterDAO;

    @Override
    public void process(ResultItems resultItems, Task task) {
        Map<String, Object> all = resultItems.getAll();

        String pageType = all.get("pageType").toString();
        if ("home".equals(pageType)) {
            saveArticle(articleDAO, SourceEnum.QISHUTA, Long.valueOf(all.get("articleId").toString())
                    , String.valueOf(all.get("title"))
                    , String.valueOf(all.get("author"))
                    , String.valueOf(all.get("url"))
            );
            return;
        }
        if ("list".equals(pageType)) {
            Long atId = Long.valueOf(all.get("articleId").toString());
            List<String> urlList = (List<String>) all.get("urlList");
            List<String> textList = (List<String>) all.get("textList");
            for (int i = 0; i < urlList.size(); i++) {
                String url = urlList.get(i);
                String name = textList.get(i);
                String[] split = url.split("/");
                String chapterId = split[split.length - 1].replace(".html", "");
                saveChapter(articleDAO, chapterDAO, SourceEnum.QISHUTA, atId, Long.valueOf(chapterId), name, url);
            }
            return;
        }
        if ("chapter".equals(pageType)) {
            Long atId = Long.valueOf(all.get("articleId").toString());
            Long ctId = Long.valueOf(all.get("chapterId").toString());
            String content = String.valueOf(all.get("content"));
            String chapterTitle = String.valueOf(all.get("chapterTitle"));
            String url = String.valueOf(all.get("url"));
            saveChapterContent(articleDAO, chapterDAO, SourceEnum.QISHUTA, atId, ctId, chapterTitle, url, content, false);
        }
    }
}
